package com.dly.blog.filter;

import com.dly.blog.exception.AuthExceptionEnum;
import com.dly.blog.provider.user.TokenProvider;
import com.dly.blog.security.UserAuth;
import com.dly.blog.service.UserDetailsAuthService;
import com.dly.blog.token.EmailToken;
import com.dly.blog.utile.JwtService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;
import java.util.Objects;
import java.util.Optional;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtService jwtService;

    private final UserDetailsAuthService userDetailsService;

    private final TokenProvider tokenProvider;

    private final HandlerExceptionResolver handlerExceptionResolver;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //如果是认证的相关Api 放行
        if (request.getServletPath().contains("/auth")) {
            filterChain.doFilter(request, response);
            return;
        }

        //没有认证头 放行
        final String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        final String jwt;
        String userId = null;

        //获取jwt
        jwt = authHeader.substring(7);

        //获取用户邮箱
        try {
            userId = jwtService.extractUsername(jwt);
        }catch (Exception e){
            //需要通过这个来抛出自定义异常处理
            handlerExceptionResolver.resolveException(request, response, null, AuthExceptionEnum.JWT_EXPIRED.getAuthException());
            return;
        }

        //如果是 没有登入 直接使用token来调用
        if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserAuth userDetails = (UserAuth) this.userDetailsService.loadUserById(userId);

            //这里会去判断token是否有效
            Boolean isTokenValid = Optional.ofNullable(tokenProvider.selectByToken(jwt))
                    .map(t -> Objects.equals(t.getIsExpired(), 0) && Objects.equals(t.getIsRevoked(), 0))
                    .orElse(false);
            //校验用户且token有效
            if(jwtService.isTokenValid(jwt, userDetails) && isTokenValid){

                EmailToken emailToken = new EmailToken(userDetails, null, userDetails.getAuthorities());

                // 设置请求的详细信息到 Authentication 对象中
                emailToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 设置security的认证token
                SecurityContextHolder.getContext().setAuthentication(emailToken);
            }

        }
        //放行
        filterChain.doFilter(request, response);
    }
}
